<template>
  <div class="my-demands-container" v-loading="loading">
    <!-- 顶部搜索工具栏 -->
    <div class="search-toolbar">
      <!-- <div>
        <el-input
          v-model="keyword"
          placeholder="请输入需求名称/资源名称/数源单位等关键字"
          clearable
          @keyup.enter="fetchData"
        >
          <template #append>
            <div class="search-button" @click="fetchData">
              <img src="@/assets/imgs/home/search.png" />
              <span>搜索</span>
            </div>
          </template>
        </el-input>
      </div> -->
    </div>

    <!-- 结果统计 -->
    <div class="result-sort-container">
      <div class="result-count">
        共有<span class="result-count-number">
          {{ total }}
        </span>
        个结果
      </div>
    </div>

    <!-- 收藏卡片列表 -->
    <div class="demand-cards-container">
      <template v-if="tableData.length > 0">
        <div v-for="item in tableData" :key="item.menuId" class="demand-card-item">
          <!-- 标题行 -->
          <div class="card-header">
            <div class="card-header-content">
              <span class="card-title">{{ item.catalogName }}</span>
            </div>

            <div class="card-actions">
              <el-button link type="primary" @click="handleView(item)">查看</el-button>
              <el-button link type="danger" @click="toggleCollect(item)">取消收藏</el-button>
            </div>
          </div>

          <!-- 摘要信息 -->
          <div class="card-summary">
            <div class="summary-item">
              <span class="summary-label">提供方：</span>
              <span class="summary-value">{{ item.deptName }}</span>
            </div>
          </div>

          <!-- 底部信息 -->
          <div class="card-footer">
            <div class="info-item">
              <img src="@/assets/imgs/data/time.png" />
              <span>收藏时间：{{ formatUpdateTime(item.updateTime) }}</span>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="!loading">
        <el-empty description="暂无收藏数据" />
      </template>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 40, 80]"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="checkCollections"
        @size-change="checkCollections"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as PortalApi from '@/api/portal'
import { useRouter } from 'vue-router'
const router = useRouter()
import { useSearchStore } from '@/store/modules/search'
const searchStore = useSearchStore()

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData: any = ref([])

// 格式化更新时间
const formatUpdateTime = (time: string) => {
  if (!time) return '--'
  return time.replace('T', ' ').split('.')[0]
}

const handleView = (item: any) => {
  searchStore.setKeyword(item.catalogName)
  router.push({
    path: '/dataCatalog'
  })
}

// 修改toggleCollect函数，添加API调用
const toggleCollect = async (item: any) => {
  try {
    // 调用收藏接口
    const response = await PortalApi.getCollect(item.catalogId)

    if (response) {
      await checkCollections()

      ElMessage.success('取消收藏成功')
    }
  } catch (error) {
    console.error('收藏操作失败:', error)
  }
}

const checkCollections = async () => {
  loading.value = true

  // 立即清空数据，避免叠加显示
  tableData.value = []
  try {
    const res = await PortalApi.getResourceDirectoryPage({
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      collected: 1
    })
    if (res) {
      tableData.value = res.list || []
      total.value = res.total || 0
      console.log('tableData更新后:', tableData.value)
    } else {
      tableData.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取收藏列表失败:', error)
    ElMessage.error('获取收藏列表失败')
    tableData.value = []
    total.value = 0
  } finally {
    loading.value = false
    console.log('数据加载完成')
  }
}

onMounted(() => {
  checkCollections()
})
</script>

<style scoped lang="scss">
.my-demands-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;

  .search-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;

    :deep(.el-input__wrapper) {
      width: 450px;
      height: 50px;
    }

    :deep(.el-input-group__append) {
      width: 100px;
      background-color: #ffffff;
      padding: 2px;
    }

    :deep(.el-input-group__append) {
      width: 130px;
    }

    .search-button {
      cursor: pointer;
      margin: 0;
      width: 100%;
      height: 100%;
      padding: 0;
      background-color: #17a7ff;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #ffffff;

      img {
        width: 16px;
        height: 16px;
        margin-right: 8px;
      }
    }
  }

  .result-sort-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .result-count {
    font-size: 14px;
    color: #999999;

    .result-count-number {
      font-size: 18px;
      color: #1faaff;
      margin: 0 8px;
    }
  }

  .demand-cards-container {
    flex: 1;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 16px;
    min-height: 300px;
    justify-content: center;
    align-items: center;
  }

  // 当有数据时恢复正常布局
  .demand-cards-container:has(.demand-card-item) {
    justify-content: flex-start;
    align-items: stretch;
  }

  .demand-card-item {
    background: #fff url('@/assets/imgs/data/back-data.png') no-repeat center center;
    background-size: cover;
    border-radius: 4px;
    padding: 16px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    display: flex;
    flex-direction: column;
    position: relative;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 12px;

      .card-header-content {
        display: flex;
        align-items: center;

        .card-title {
          font-size: 18px;
          font-weight: 500;
          color: #303133;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          max-width: 400px;
        }
      }

      .card-actions {
        display: flex;
        align-items: center;
        gap: 8px;
        color: #17a7ff !important;
        font-size: 16px;
        cursor: pointer;
      }
    }

    .card-summary {
      margin-bottom: 12px;

      .summary-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        font-size: 14px;
        color: #606266;

        .summary-label {
          font-weight: 500;
          // min-width: 80px;
          color: #909399;
        }

        .summary-value {
          color: #303133;
        }
      }
    }

    .card-footer {
      font-size: 13px;
      color: #909399;
      display: flex;
      gap: 50px;

      .info-item {
        display: flex;
        align-items: center;
        gap: 4px;

        img {
          width: 16px;
          height: 16px;
        }
      }
    }
  }

  .pagination-container {
    margin-top: 16px;
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 12px;

    .page-size-selector {
      display: flex;
      align-items: center;
      font-size: 14px;
      color: #606266;
      cursor: pointer;
    }
  }
}
</style>
